<template>
  <view class="container">
    <div class="border-content">
      <div style="height: 10px"></div>
      <!-- 地图 -->
      <!-- <div class="maps">
          <map name="map" style="height: 260px; width: 100%"></map>
        </div> -->
      <div style="height: 10px"></div>
      <!-- 表单展示 -->
      <!-- <div style="color: #718778">
          <div class="form-flex">
            <div class="border-max" style="width: 49%;">
              <div style="height: 5rpx"></div>
              <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
                <div style="height:5rpx"></div>
                <input disabled v-model="launchTime" type="text">
                <div style="height:5rpx"></div>
              </picker>
              <div style="height: 5rpx"></div>
            </div>
            <div class="border-max" style="width: 49%;">
              <div style="height: 5rpx"></div>
              <picker mode="time" :value="time" start="09:01" end="21:01" @change="bindTimeChange">
                <div style="height:5rpx"></div>
                <input disabled v-model="datatime" type="text">
                <div style="height:5rpx"></div>
              </picker>
              <div style="height: 5rpx"></div>
            </div>
          </div>
          <div style="height: 10px"></div>
          <div class="form-flex">
            <div style="width: 15%; color: #1a512c; font-weight: 500">
              收运车
            </div>
            <div class="borders" style="width: 85%">
              <div style="height: 5rpx"></div>
              <picker @change="bindPickerChange" :value="index" :range="carList">
                <div style="height:5rpx"></div>
                <input placeholder="请选择收运车" disabled v-model="licenseNumber" type="text">
                <div style="height:5rpx"></div>
              </picker>
              <div style="height: 5rpx"></div>
            </div>
          </div>
          <div style="height: 10px"></div>
          <div style="display: flex; align-items: center">
            <div class="flex">
              <div style="width: 30%; color: #1a512c; font-weight: 500">
                车类型
              </div>
              <div style="width: 69%" class="borders-min">
                <div style="height:5rpx"></div>
                <input placeholder="自动显示" v-model="carTypeName" disabled type="text" />
                <div style="height:5rpx"></div>
              </div>
            </div>
            <div style="width: 10rpx"></div>
            <div class="flex">
              <div style="width: 30%; color: #1a512c; font-weight: 500">
                有机质
              </div>
              <div style="width: 69%" class="borders-min">
                <div style="height:5rpx"></div>
                <input placeholder="自动显示" disabled v-model="vehicleOrganicType" type="text" />
                <div style="height:5rpx"></div>
              </div>
            </div>
          </div>
          <div style="height: 10px"></div>
          <div style="display: flex; align-items: center">
            <div class="flex">
              <div style="width: 30%; color: #1a512c; font-weight: 500">
                司机
              </div>
              <div style="width: 69%" class="borders-min">
                <picker @change="bindPickerDriver" :value="index" :range="driverList">
                  <div style="height:5rpx"></div>
                  <input placeholder="自动显示" disabled v-model="driverName" type="text" />
                  <div style="height:5rpx"></div>
                </picker>
              </div>
            </div>
            <div style="width: 10rpx"></div>
            <div class="flex">
              <div style="width: 30%; color: #1a512c; font-weight: 500">
                电话
              </div>
              <div style="width: 69%" class="borders-min">
                <picker @change="bindPickerDriver" :value="index" :range="driverList">
                  <div style="height:5rpx"></div>
                  <input placeholder="自动显示" v-model="driverPhone" disabled type="text" />
                  <div style="height:5rpx"></div>
                </picker>
              </div>
            </div>
          </div>
          <div style="height: 10px"></div>
          <div v-for="(item, index) in form">
            <div style="display: flex; align-items: center;justify-content: space-between;">
              <div style="display: flex; width: 25%;align-items: center;">
                <image @click="deleArr(item, index)" mode="widthFix"
                  src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fdel.png"
                  style="width: 50rpx;height: 50rpx;" />
                <div style="width: 10rpx"></div>
                <div style="color: #1a512c; font-weight: 500">收运点</div>
              </div>
              <div class="borders" style="width: 75%">
                <picker @change="(event) => bindPickerChanges(event, index)" :value="index" :range="farmLists">
                  <div style="height:5rpx"></div>
                  <input placeholder="点击选择收运点" disabled v-model="item.farmName" type="text">
                  <div style="height:5rpx"></div>
                </picker>
              </div>
            </div>
            <div style="height: 30rpx"></div>
            <u-line color="#C2C9C4"></u-line>
            <div style="height: 30rpx"></div>
          </div>
        </div> -->

      <!-- <div style="display: flex; align-items: center; justify-content: center" @click="pushArr">
          <image src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/static%2Fadd.png"
            style="height: 50rpx;height: 50rpx;" mode="widthFix" />
          <div style="width: 10rpx"></div>
          <div>新增收运点</div>
        </div> -->
      <div class="card">
        <div style="width: 90%;margin-left: 5%;">
          <div style="height: 10px;"></div>
          <div style="font-size: 18px;font-weight: 500;">基础信息</div>
          <div style="height: 10px;"></div>
          <u-line color="#f1f1f1"></u-line>
          <div style="height: 10px;"></div>
          <div class="newFlex">
            <div>日期</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
                <input style="height: 42px;" disabled v-model="launchTime" type="text">
              </picker>
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div class="newFlex">
            <div>时间</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <picker mode="time" :value="time" start="09:01" end="21:01" @change="bindTimeChange">
                <input style="height: 42px;" disabled v-model="datatime" type="text">
              </picker>
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div class="newFlex">
            <div>收运车辆</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <picker @change="bindPickerChange" :value="index" :range="carList">
                <input style="height: 42px;" placeholder="请选择收运车" disabled v-model="licenseNumber" type="text">
              </picker>
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div class="newFlex">
            <div>有机质类型</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <input placeholder="自动显示" disabled v-model="vehicleOrganicType" type="text" />
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div class="newFlex">
            <div>司机姓名</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <picker @change="bindPickerDriver" :value="index" :range="driverList">
                <input placeholder="自动显示" disabled v-model="driverName" type="text" />
              </picker>
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div class="newFlex">
            <div>司机电话</div>
            <div style="height: 15rpx;"></div>
            <div class="borders">
              <input placeholder="自动显示" v-model="driverPhone" disabled type="text" />
            </div>
          </div>
          <div style="height: 15px;"></div>
        </div>
      </div>
      <div style="height: 10px;"></div>
      <div class="card">
        <div style="width: 90%;margin-left: 5%;">
          <div style="height: 10px;"></div>
          <div style="font-size: 18px;font-weight: 500;">收运点信息</div>
          <div style="height: 10px;"></div>
          <u-line color="#f1f1f1"></u-line>
          <div v-for="(item, index) in form" style="margin-top: 10px;">
            <div class="newFlex">
              <div style="display: flex;align-items: center;justify-content: space-between;">
                <div>收运点</div>
                <image v-if="index != 0" @click="deleArr(item, index)"
                  src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/%E9%9D%92%E5%B2%9B%E5%B0%8F%E7%A8%8B%E5%BA%8F%2FFrame.png"
                  style="width: 50rpx;height: 50rpx;" />
              </div>
              <div style="height: 15rpx;"></div>
              <div class="borders">
                <picker @change="(event) => bindPickerChanges(event, index)" :value="index" :range="farmLists">
                  <input placeholder="点击选择收运点" disabled v-model="item.farmName" type="text">
                </picker>
              </div>
            </div>
          </div>
          <div style="height: 15px;"></div>
          <div style="display: flex;justify-content: center;">
            <div style="display: flex;align-items: center;" @click="pushArr">
              <image
                src="https://28-1325662301.cos.ap-shanghai.myqcloud.com/%E9%9D%92%E5%B2%9B%E5%B0%8F%E7%A8%8B%E5%BA%8F%2FFrame%20(1).png"
                style="width: 50rpx;height: 50rpx;" />
              <div>新增收运点</div>
            </div>
          </div>
          <div style="height: 15px;"></div>
        </div>
      </div>
      <div style="height: 15px;"></div>
      <div class="card">
        <div style="height: 15px;"></div>
        <div class="button-footers" @click="lookMap">预览线路</div>
        <div style="height: 10px;"></div>
        <div class="button-footer" @click="send">派发工单</div>
        <div style="height: 15px;"></div>
      </div>
      <div style="height: 2vh;"></div>

    </div>
  </view>
</template>
<script>
import { optionList, addSend, farmList, driverLists, getMapJSON } from '../../common/example.js';
export default {
  data() {
    const currentDate = this.getDate({
      format: true
    })
    return {
      indent: '',
      form: [
        {
          farmName: '',
          farmId: '',
        },
      ],
      carList: [],
      carFilter: [],
      farmListFind: [],
      farmLists: [],
      currentPage: '',
      role: '',
      farmName: '',
      // 
      carTypeName: '',
      driverName: '',
      driverPhone: '',
      carId: '',
      driverId: '',
      licenseNumber: '',
      vehicleOrganicType: '',
      vehicleType: '',
      launchTime: currentDate,
      time: '09:01',
      id: '',
      driverList: [],
      findDriver: [],
      datatime: ''
    };
  },
  computed: {
    startDate() {
      return this.getDate('start');
    },
    endDate() {
      return this.getDate('end');
    }
  },
  methods: {
    lookMap() {
      console.log(this.form);
      if (this.form[0].farmId == '') {
        uni.showToast({
          title: '请选择收运点',
          icon: 'none'
        })
      } else {
        let ids = this.form.map((item) => item.farmId);
        uni.navigateTo({
          url: `/pagesDispatch/index/map?id=${ids}`
        });
      }

    },
    getDate(type) {
      const date = new Date();
      let year = date.getFullYear();
      let month = date.getMonth() + 1;
      let day = date.getDate();

      if (type === 'start') {
        year = year - 60;
      } else if (type === 'end') {
        year = year + 2;
      }
      month = month > 9 ? month : '0' + month;
      day = day > 9 ? day : '0' + day;
      return `${year}-${month}-${day}`;
    },
    pushArr() {
      this.form.push({
        farmName: '',
        farmId: '',
      });
    },
    deleArr(i, index) {
      if (this.form.length == 1) {
        uni.showToast({
          title: "必须保留一个",
          icon: "none",
          mask: true,
        });
        this.getFarm();
      } else {
        this.form.splice(index, 1);
      }
    },
    bindTimeChange: function (e) {
      this.datatime = e.detail.value + ':00'
    },
    bindPickerChange: function (e) {
      console.log('picker发送选择改变，携带值为', e.detail.value)
      const value = e.detail.value;
      console.log(this.carFilter[value], '选中value');
      const checkedValue = this.carFilter[value];
      this.driverName = checkedValue.driverName;
      this.driverPhone = checkedValue.driverPhone;
      this.carTypeName = checkedValue.vehicleType == 0 ? '收运车' : '自派车';
      this.driverId = checkedValue.driverId;
      this.licenseNumber = checkedValue.licenseNumber;
      this.vehicleOrganicType = checkedValue.organicType;
      this.vehicleType = checkedValue.vehicleType;
      this.id = checkedValue.id;
    },
    bindPickerChanges(e, index) {

      const value = e.detail.value;
      console.log(value, 'value');
      this.form[index].farmId = this.farmListFind[value].id;
      this.form[index].farmName = this.farmListFind[value].farmName;
      // this.farmLists.splice(value, 1);
      // this.farmListFind.splice(value,1);
      // console.log(this.form[index].farmName,'this.form[index].farmName');

      // console.log(this.farmLists, 'farmLists');
      // console.log(this.farmListFind,'farmListFind');
    },
    bindDateChange: function (e) {
      this.launchTime = e.detail.value
    },
    bindPickerDriver(e) {
      const value = e.detail.value;
      console.log(value);
      const obj = this.findDriver[value];
      console.log(obj, 'obj');
      this.driverName = obj.nickName;
      this.driverPhone = obj.phonenumber;
      this.driverId = obj.userId;
    },
    //派发
    send() {
      const self = this;
      let flag;
      const newArr = self.form.map(({ farmName, ...rest }) => rest);
      console.log(newArr, 'newArr');
      const farmIds = newArr.map(item => item.farmId);
      const hasDuplicates = new Set(farmIds).size !== farmIds.length;

      if (hasDuplicates) {
        console.log('有重复的 farmId！');
      } else {
        console.log('没有重复的 farmId。');
      }
      for (let i = 0; i < newArr.length; i++) {
        if (newArr[i].farmId == '') {
          uni.showToast({
            title: '请选择收运点',
            icon: 'none'
          })
          flag = false;
        } else {
          flag = true;
        }
      }
      if (self.id == '' || self.newArr == '' || self.driverName == '') {
        uni.showToast({
          title: '请输入完整',
          icon: 'none'
        })
      } else if (flag == false) {
        uni.showToast({
          title: '请选择收运点',
          icon: 'none'
        })
      } else if (hasDuplicates) {
        uni.showToast({
          title: '不能选择重复的收运点',
          icon: 'none'
        })
      } else {
        // 获取json后调用派单接口
        let ids = self.form.map((item) => item.farmId)
        getMapJSON(ids).then(response => {
          console.log(response.data.data, 'json');
          if (response.data.code == 200) {
            let json = JSON.stringify(response.data.data)
            // 调用派单接口
            addSend({
              vehicleId: self.id,
              workOrderDetailList: newArr,
              licenseNumber: self.licenseNumber,
              driverId: self.driverId,
              launchTime: self.launchTime + ' ' + self.datatime,
              driverName: self.driverName,
              driverPhone: self.driverPhone,
              vehicleOrganicType: self.vehicleOrganicType,
              vehicleType: self.vehicleType,
              transportationRoute: json
            }).then(res => {
              console.log(res, 'add');
              if (res.code == 200) {
                uni.showToast({
                  title: res.msg,
                  icon: 'success'
                });
                setTimeout(() => {
                  self.driverName = '';
                  self.driverPhone = '';
                  self.vehicleType = '';
                  self.launchTime = '';
                  self.driverId = '';
                  self.licenseNumber = '';
                  self.id = '';
                  self.vehicleType = ''
                  self.vehicleOrganicType = '';
                  self.carTypeName = '';
                  uni.redirectTo({
                    url: '/pagesScreen/index/home'
                  })
                }, 1000);
                // self.form = { farmId: '', farmName: '' };
              } else {
                uni.showToast({
                  title: res.data.msg,
                  icon: 'none'
                });
                setTimeout(() => {
                  self.driverName = '';
                  self.driverPhone = '';
                  self.vehicleType = '';
                  self.launchTime = '';
                  self.driverId = '';
                  self.licenseNumber = '';
                  self.id = '';
                  self.vehicleType = ''
                  self.vehicleOrganicType = '';
                  self.carTypeName = '';
                  uni.redirectTo({
                    url: '/pagesScreen/index/pagesCopyhome'
                  })
                }, 1000);
              }
            }).catch(err => {
              console.log(err, 'err');
              uni.showToast({
                title: err.msg,
                icon: 'none'
              });
            })
          }
        })

      }

    },
    clearForm() {
      this.form = { farmId: '', farmName: '' };
      this.driverName = '';
      this.driverPhone = '';
      this.vehicleType = '';
      this.launchTime = '';
      this.driverId = '';
      this.licenseNumber = '';
      this.id = '';
    },
    // time
    //获取当前时间
    Fun_date() {
      let date = new Date();
      let hours = date.getHours();//小时
      let minute = date.getMinutes();//分
      let second = date.getSeconds();//秒
      let time = this.Fun_fnW(hours) + ":" + this.Fun_fnW(minute) + ":" + this.Fun_fnW(second);
      this.datatime = time;
      // console.log(this.datatime);
    },

    //当某个字段不是两位数时补0
    Fun_fnW(str) {
      let num = str.toString(); // 将数字转换为字符串
      return num.padStart(2, '0'); // 使用padStart方法补零
    },
    getFarm() {
      farmList().then(res => {
        console.log(res, 'farmList');
        this.farmLists = res.data.data.map((item) => item.farmName);
        this.farmListFind = res.data.data;
      })
    }
  },
  onShow() {
    this.indent = uni.getStorageSync('pageIndent');
    this.role = uni.getStorageSync('userInfo').remark;
    var pages = getCurrentPages();
    let currentPageRoute = pages[pages.length - 1].route;
    // 根据当前页面路径设置currentPage
    this.currentPage = currentPageRoute;
    console.log(this.currentPage);
    // 车辆列表
    optionList().then(res => {
      console.log(res.data, 'res-carList');
      this.carList = res.data.data.map(item => `${item.licenseNumber}(${item.organicType})`);
      this.carFilter = res.data.data;
    })
    driverLists().then(res => {
      console.log(res.data, 'carLIst');
      this.findDriver = res.data.rows;
      // this.driverList = res.data.rows.map((item)=>item.nickName);
      this.driverList = res.data.rows.map((item) => `${item.nickName}(${item.phonenumber})`)
    })
    // 产生单位列表
    this.getFarm();
  },
  onLoad() {
    let that = this;
    // setInterval(function () {
    that.Fun_date();
    // }, 1000);

  }
};
</script>
<style lang="scss">
input {
  height: 42px;
}

.card {
  background: #fff;
  border-radius: 10px;
}

.container {
  background: #f3f3f3;
  height: 100vh;
  overflow-y: scroll;

  .border-content {
    width: 90%;
    margin-left: 5%;
  }
}

.top-line {
  display: flex;
  align-items: center;
}

.line {
  background: #1a512c;
  width: 7rpx;
  height: 35rpx;
}

.maps {
  border: 2px solid #1a512c;
  overflow: hidden;
  border-radius: 10px;
}

.form-flex {
  display: flex;
  align-items: center;
  width: 100%;
  justify-content: space-between
}

.borders {
  border: 1px solid #000000;
  border-radius: 5px;
  text-align: center;
}

.border-max {
  border: 1px solid #1a512c;
  border-radius: 5px;
  text-align: center;
  width: 100%;
}

.borders-min {
  border: 1px solid #1a512c;
  border-radius: 5px;
  text-align: center;
}

.footer {
  // display: flex;
  // align-items: center;
  // justify-content: center;
}

.button-footer {
  width: 90%;
  margin-left: 5%;
  height: 45px;
  background: #000000;
  border: 1px solid #000000;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  border-radius: 5px;
}

.button-footers {
  width: 90%;
  margin-left: 5%;
  height: 45px;
  background: #ffffff;
  border: 1px solid #000000;
  color: #000000;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 18px;
  font-weight: 500;
  border-radius: 5px;
}

.flex {
  display: flex;
  align-items: center;
}

.addIcon {
  border-radius: 50%;
  border: 1px solid #1a512c;
  font-weight: 500;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
}
</style>
